//
//  ImageZoomView.m
//  jingdongfang
//
//  Created by MTiMac01 on 2017/9/8.
//  Copyright © 2017年 LJL. All rights reserved.
//

#import "ImageZoomView.h"
#import "SDBrowserImageView.h"
#import "SDWaitingView.h"

@interface ImageZoomView ()<UIScrollViewDelegate>
{
    __weak SDWaitingView *_waitingView;
    UIScrollView *holderView;
    UIScrollView *_zoomingScroolView;
    UIImageView *showImgView;
    CGAffineTransform transForm;
    CGFloat _totalScale;

}
@end

@implementation ImageZoomView

- (instancetype)initWithFrame:(CGRect)frame andWithImage:(NSString *)imageUrl type:(NSString *)plates scale:(CGFloat)scale placeholderImage:(UIImage *)image
{
    if(self = [super initWithFrame:frame])
    {
        holderView = [[UIScrollView alloc] initWithFrame:frame];
        holderView.backgroundColor=[UIColor blackColor];
        holderView.contentSize = self.bounds.size;
        holderView.showsHorizontalScrollIndicator = NO;
        holderView.showsVerticalScrollIndicator = NO;
        holderView.delegate = self;
        [holderView setAlpha:0];
        [self addSubview:holderView];
        
        SDWaitingView *waiting = [[SDWaitingView alloc] init];
        waiting.bounds = CGRectMake(0, 0, 100, 100);
        waiting.mode = SDWaitingViewProgressMode;
        _waitingView = waiting;
        [self addSubview:waiting];
        
        showImgView = [[UIImageView alloc] init];
        [showImgView sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:image options:SDWebImageCacheMemoryOnly progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
    
            float currentProgress = (float)receivedSize/(float)expectedSize;
            _waitingView.progress = currentProgress;
            dispatch_async(dispatch_get_main_queue(), ^{
                        [self bringSubviewToFront:_waitingView];
            });
        } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            [_waitingView removeFromSuperview];
            
        }];
        showImgView.userInteractionEnabled = YES;
        showImgView.multipleTouchEnabled = YES;
        showImgView.contentMode = UIViewContentModeScaleAspectFit;
        [holderView addSubview:showImgView];
        
        CGFloat y,width,height;
        //宽度为屏幕宽度
        width = [UIScreen mainScreen].bounds.size.width - 80;
        y = ([UIScreen mainScreen].bounds.size.height - width * 16 / 9) * 0.5;
        //高度 根据图片宽高比设置
        height = width * 16 / 9;
        if ([plates integerValue] == 1)
        {
            showImgView.size = CGSizeMake(height, width);
            showImgView.center = self.center;
            transForm = CGAffineTransformMakeRotation(-M_PI/2);
        }
        else if ([plates integerValue] == 2)
        {
            transForm = CGAffineTransformMakeRotation(0);
            [showImgView setFrame:CGRectMake(40, y, width, height)];
        }
        else
        {
            transForm = CGAffineTransformMakeRotation(0);
            if(KSCREENWIDTH/scale <= KSCREENHEIGHT)
            {
                showImgView.size = CGSizeMake(KSCREENWIDTH, KSCREENWIDTH/scale);
            }
            else
            {
                showImgView.size = CGSizeMake(KSCREENHEIGHT * scale, KSCREENHEIGHT);
            }
            showImgView.center = self.center;
        }
        showImgView.transform = transForm;

        //动画放大所展示的ImageView
        [UIView animateWithDuration:0.4 animations:^{
            [holderView setAlpha:1];
        } completion:^(BOOL finished) {

        }];
        
        UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(zoomImage:)];
        _totalScale = 1.0;
        [showImgView addGestureRecognizer:pinchGestureRecognizer];
        //// 单击图片
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(photoClick:)];
        [singleTap setNumberOfTapsRequired:1];
        [showImgView addGestureRecognizer:singleTap];
    }
    return self;
}

- (void)zoomImage:(UIPinchGestureRecognizer *)recognizer
{
//    [self prepareForImageViewScaling];
    CGFloat scale = recognizer.scale;
    CGFloat temp = _totalScale + (scale - 1);
    [self setTotalScale:temp];
    recognizer.scale = 1.0;
}

- (void)setTotalScale:(CGFloat)totalScale
{
    if ((_totalScale < 0.5 && totalScale < _totalScale) || (_totalScale > 2.0 && totalScale > _totalScale)) return; // 最大缩放 2倍,最小0.5倍
    [self zoomWithScale:totalScale];
}

- (void)zoomWithScale:(CGFloat)scale
{
    _totalScale = scale;
    
    showImgView.transform = CGAffineTransformScale(transForm, scale, scale);

    if (scale > 1)
    {
        CGFloat contentW = MAX(showImgView.frame.size.width, KSCREENWIDTH);
        CGFloat contentH = MAX(showImgView.frame.size.height, self.frame.size.height);
        
        showImgView.center = CGPointMake(contentW * 0.5, contentH * 0.5);
        holderView.contentSize = CGSizeMake(contentW, contentH);
        
        
        CGPoint offset = holderView.contentOffset;
        offset.x = (contentW - holderView.frame.size.width) * 0.5;
        //        offset.y = (contentH - _zoomingImageView.frame.size.height) * 0.5;
        holderView.contentOffset = offset;
    } else {
        holderView.contentSize = holderView.frame.size;
        holderView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        showImgView.center = holderView.center;
    }
}


//-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
//{
//      return showImgView;
//}

//- (void)prepareForImageViewScaling
//{
//    if (!_zoomingScroolView) {
//        _zoomingScroolView = [[UIScrollView alloc] initWithFrame:self.bounds];
//        _zoomingScroolView.backgroundColor = SDPhotoBrowserBackgrounColor;
//        _zoomingScroolView.contentSize = self.bounds.size;
//        UIImageView *zoomingImageView = [[UIImageView alloc] initWithImage:self.image];
//        CGSize imageSize = zoomingImageView.image.size;
//        CGFloat imageViewH = self.bounds.size.height;
//        if (imageSize.width > 0) {
//            imageViewH = self.bounds.size.width * (imageSize.height / imageSize.width);
//        }
//        zoomingImageView.bounds = CGRectMake(0, 0, self.bounds.size.width, imageViewH);
//        zoomingImageView.center = _zoomingScroolView.center;
//        zoomingImageView.contentMode = UIViewContentModeScaleAspectFit;
//        _zoomingImageView = zoomingImageView;
//        [_zoomingScroolView addSubview:zoomingImageView];
//        [self addSubview:_zoomingScroolView];
//    }
//}


- (void)photoClick:(UITapGestureRecognizer*)tap
{
    [UIView animateWithDuration:0.4 animations:^{
        [holderView setAlpha:0];
    } completion:^(BOOL finished) {
        //完成后操作->将背景视图删掉
        [holderView removeFromSuperview];
        [self removeFromSuperview];
    }];
    
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    _waitingView.center = CGPointMake(self.frame.size.width * 0.5, self.frame.size.height * 0.5);
}

@end
